<!--
  @Name: saleQuery.vue
  @Description: 渠道产品信息 - 销量查询
  @Author: huangcy@zlsoft.cn
  @CreateDate: 2023/6/27
 -->
<template>
  <div>
    <!--  产品销售  -->
    <div class="box" v-for="(item,index) in arr" :key="index">
      <div class="box-head">
        <div>{{ name ? name : index === 0 ? '产品销售' : '供应商' }}</div>
        <div>
          <div :class="{active: params[item + 'Params'].dateType==='month'}"
               @click="handleChangeMonth(item)">按月切换
          </div>
          <div :class="{active: params[item + 'Params'].dateType==='day'}"
               @click="handleChangeDay(item,'')">按天切换
          </div>
        </div>
      </div>
      <div class="box-content">
        <div>
          年份：
          <el-date-picker
            v-model="params[item+'Params'].year"
            type="year"
            value-format="yyyy"
            placeholder="选择年"
            style="width: 120px"
            @change="initData(item)"
          />
          <span v-if="params[item+'Params'].dateType === 'day'">
            月份：
            <el-select v-model="params[item+'Params'].month" style="width: 120px"
                       @change="handleChangeDay(item,$event)">
              <el-option v-for="({label,value}) in monthList" :key="value" :label="label" :value="value"/>
            </el-select>
          </span>
          <span v-if="item === 'supplierEcharts' && !isNoChannel">
          供应商名称：
          <el-input
            v-model="params[item+'Params'].supplierName"
            style="width:140px;"
            placeholder="请输入供应商名称"
            @input="handleInput"
          />
          </span>
          <span v-if="!isNoChannel">
          产品：
          <table-select
            :tableColumns=" [
                    {prop:'code',label:'商品编码',width:'100'},
                  {prop:'name',label:'商品名称',width: '280'}
                  ]"
            labelKey="name"
            valueKey="id"
            :value.sync="params[item+'Params'].goodsIds"
            placeholder="请选择产品"
            url="/api/dropDown/jstGoodsList"
            style="width:160px;display: inline-block"
            @change="initData(item)"
          />
          </span>
          <span v-if="!isNoChannel">
            渠道：
          <table-select
            :tableColumns="[
              {prop:'code',label:'渠道编码',width:'100'},
              {prop:'name',label:'渠道名称',width: '280'}
              ]"
            labelKey="name"
            valueKey="id"
            :value.sync="params[item+'Params'].channelIds"
            placeholder="请选择渠道"
            url="/api/dropDown/jstChannelList"
            style="width:160px;display: inline-block"
            @change="initData(item)"
          />
          </span>
        </div>
        <div :id="item" v-loading="params[item+'Load']"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { querySale } from '@/api/erp/jstChannelGoods'

export default {
  props: ['arr', 'name', 'isNoChannel','channelIds','goodsIds'],
  data() {
    return {
      params: {
        // 产品销售柱状图
        productEcharts: null,
        // 供应商销售柱状图
        supplierEcharts: null,
        // 查询参数
        productEchartsParams: {
          dateType: 'month',
          month: '',
          year: ''
        },
        supplierEchartsParams: {
          dateType: 'month',
          month: '',
          year: '',
          supplierName: ''
        },
        // x轴数据
        productEchartsXData: [],
        supplierEchartsXData: [],
        // 数据
        productEchartsData: [],
        supplierEchartsData: [],
        // load
        productEchartsLoad: [],
        supplierEchartsLoad: []
      },
      timeout: null
    }
  },
  watch:{
    channelIds:{
      handler(){
        this.arr.map(i => {
          this.params[i + 'Params'].channelIds = this.channelIds || ''
          this.handleChangeMonth(i)
        })
      },immediate:true
    },
    goodsIds:{
      handler(){
        this.arr.map(i => {
          this.params[i + 'Params'].goodsIds = this.goodsIds || ''
          this.handleChangeMonth(i)
        })
      },immediate:true
    }
  },
  mounted() {
    if (this.arr) {
      this.arr.map(i => {
        this.params[i + 'Params'].year = new Date().getFullYear().toString()
        this.params[i + 'Params'].channelIds = this.channelIds || ''
        this.params[i + 'Params'].goodsIds = this.goodsIds || ''
        this.handleChangeMonth(i)
      })
    }
  },
  computed: {
    monthList() {
      let arr = []
      for (let i = 1; i < 13; i++) {
        arr.push({ label: i + '月', value: i })
      }
      return arr
    }
  },
  methods: {
    /**
     * 获取销量数据
     */
    async initData(val) {
      this.params[val + 'Load'] = true
      const res = await querySale(this.params[val + 'Params']).finally(() => {
        this.params[val + 'Load'] = true
      })
      if (res && res.data) {
        this.params[val + 'Data'] = res.data.content && res.data.content.length > 0 ? Object.values(res.data.content[0]) : []
        this.initEcharts(val)
      }
    },
    /**
     * 初始化产品销售、供应商柱状图
     */
    initEcharts(val) {
      this.params[val] && this.$echarts.dispose(document.getElementById(val))
      this.params[val] = this.$echarts.init(document.getElementById(val))
      // 柱状图参数
      const option = {
        grid: {
          left: 'auto',
          right: '10px',
          bottom: '20px',
          top: '20px',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.params[val + 'XData']
        },
        color: '#0882d6',
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.params[val + 'Data'],
            type: 'bar'
          }
        ]
      }
      this.params[val].setOption(option)
    },
    /**
     * 按月切换
     */
    handleChangeMonth(val) {
      this.params[val + 'Params'].dateType = 'month'
      this.params[val + 'XData'] = []
      for (let i = 1; i < 13; i++) {
        this.params[val + 'XData'].push(i + '月')
      }
      this.initData(val)
    },
    /**
     * 按天切换
     */
    handleChangeDay(val, month) {
      this.params[val + 'Params'].dateType = 'day'
      this.params[val + 'XData'] = []
      !month ? this.params[val + 'Params'].month = new Date().getMonth() + 1 : ""
      this.$set(this.params[val + 'Params'], 'month', this.params[val + 'Params'].month)

      function getMonthDays(year, month) {
        let stratDate = new Date(year, month - 1, 1),
          endData = new Date(year, month, 1);
        let days = (endData - stratDate) / (1000 * 60 * 60 * 24);
        return days;
      }

      for (let i = 1; i <= getMonthDays(this.params[val + 'Params'].year, this.params[val + 'Params'].month); i++) {
        this.params[val + 'XData'].push(i + '日')
      }
      this.initData(val)
    },
    /**
     * 输入供应商
     */
    handleInput() {
      clearTimeout(this.timeout)

      this.timeout = setTimeout(() => {
        this.initData('supplierEcharts')
      }, 1000)
    }
  }
}
</script>

<style scoped lang="scss">
.box {
  width: 100%;
  margin-top: -30px;

  & + .box {
    margin-top: 0;
  }

  &-head {
    height: 32px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 0;

    > div:first-of-type {
      position: relative;
      margin-left: 10px;
      font-size: 16px;
      font-weight: 600;

      &::before {
        position: absolute;
        content: '';
        height: 20px;
        width: 4px;
        left: -10px;
        top: calc(50% - 10px);
        background-color: #0882d6;
        border-radius: 6px;
      }
    }

    > div:last-of-type {
      display: flex;

      div {
        width: 120px;
        text-align: center;
        background-color: #e6e6e6;
        border-radius: 20px;
        height: 32px;
        line-height: 32px;
        cursor: pointer;

        & + div {
          margin-left: 10px;
        }
      }

      .active {
        color: #ffffff;
        background-color: #0882d6;
      }
    }
  }

  &-content {
    width: 100%;

    #supplierEcharts,
    #productEcharts {
      width: 100%;
      height: 240px;
    }
  }
}
</style>
